package com.tywj.lib.core.widget.recycleview.adapter

import android.view.View
import androidx.annotation.ColorRes
import androidx.annotation.IdRes
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.tywj.lib.core.common.extension.onClick
import com.tywj.lib.core.common.util.ResourcesUtil

/**
 * <pre>
 *     author : June Yang
 *     time   : 2020/5/13
 *     desc   : RecyclerView基类ViewHolder，主要是为了封装第三方框架，方便替换
 *     version: 1.0.0
 * </pre>
 */
class BaseViewHolder(view: View) : BaseViewHolder(view) {

    /**
     * 父类adapter字段引用副本，因为父类该字段为私有，在子类中不能获取到该类
     */
    private lateinit var adapterCopy: BaseAdapter<*>

    override fun setAdapter(adapter: BaseQuickAdapter<*, *>): BaseViewHolder {
        adapterCopy = adapter as BaseAdapter<*>
        return super.setAdapter(adapter)
    }

    /**
     * 添加点击监听，限定时间之内只取第一个点击事件，防止重复点击
     */
    override fun addOnClickListener(vararg viewIds: Int): BaseViewHolder {
        for (viewId in viewIds) {
            childClickViewIds.add(viewId)
            val view = getView<View>(viewId)
            view?.let {
                if (!it.isClickable) {
                    it.isClickable = true
                }
                it.onClick {
                    adapterCopy.onItemChildClickListener?.onItemChildClick(
                        adapterCopy, it, getClickPosition()
                    )
                }
            }
        }
        return this
    }

    /**
     * 添加点击监听
     */
    fun addOnClickWithoutIntervalListener(vararg viewIds: Int): BaseViewHolder {
        viewIds.forEach { super.addOnClickListener(it) }
        return this
    }

    /**
     * 设置TextView文本颜色
     */
    fun setTextColorRes(@IdRes viewId: Int, @ColorRes resId: Int): BaseViewHolder {
        setTextColor(viewId, ResourcesUtil.getColor(resId))
        return this
    }

    /**
     * 获取点击的位置。
     */
    private fun getClickPosition(): Int {
        return if (layoutPosition >= adapterCopy.headerLayoutCount) {
            layoutPosition - adapterCopy.headerLayoutCount
        } else 0
    }
}